﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;
using WinnerCMS.BLL;
using WinnerCMS.BLL.PageFactory.TagModule;
using WinnerCMS.Common;
using WinnerCMS.Model;

namespace WinnerCMS.WebFactory
{
    public static class PageCommon
    {
        private readonly static Regex Reg = new Regex("@(\\w+)@", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        #region 替换字段
        /// <summary>
        /// 替换字段
        /// </summary>
        /// <param name="tempStrBuilder"></param>
        /// <param name="dt"></param>
        static public void RepalceFiled(StringBuilder tempStrBuilder, DataTable dt)
        {
            foreach (DataColumn dc in dt.Columns)
            {
                string strProperty = string.Concat("@", dc.ColumnName, "@");
                if (dc.DataType == typeof(DateTime))
                {
                    tempStrBuilder.Replace(strProperty, Convert.ToDateTime(dt.Rows[0][dc.ColumnName]).ToString("yyyy-MM-dd"));
                }
                else
                {
                    tempStrBuilder.Replace(strProperty, dt.Rows[0][dc.ColumnName].ToString());
                }
            }
        }

        /// <summary>
        /// 替换字段
        /// </summary>
        /// <param name="tempStrBuilder"></param>
        /// <param name="model"></param>
        static public void RepalceFiled(StringBuilder tempStrBuilder, object model)
        {
            string str = tempStrBuilder.ToString();

            var matches = Reg.Matches(str);

            string[] fieldNames = new string[matches.Count];
            string[] propertyNames = new string[matches.Count];
            for (int i = 0; i < matches.Count; i++)
            {
                fieldNames[i] = matches[i].Groups[0].Value;
                propertyNames[i] = matches[i].Groups[1].Value;
            }
            Type t = model.GetType();

            for (int i = 0; i < fieldNames.Length; i++)
            {
                PropertyInfo pi = t.GetProperty(propertyNames[i]);
                if (pi == null)
                    continue;

                if (pi.PropertyType == typeof(DateTime))
                {
                    tempStrBuilder.Replace(fieldNames[i], Convert.ToDateTime(pi.GetValue(model, null)).ToString("yyyy-MM-dd"));
                }
                else
                {
                    tempStrBuilder.Replace(fieldNames[i], Convert.ToString(pi.GetValue(model, null)));
                }
            }
        }

        /// <summary>
        /// 替换字段
        /// </summary>
        /// <param name="tempStrBuilder"></param>
        /// <param name="model"></param>
        static public void RepalceFiledOld(StringBuilder tempStrBuilder, object model)
        {
            foreach (PropertyInfo pi in model.GetType().GetProperties())
            {
                object o = pi.GetValue(model, null);
                if (o == null)
                {
                    continue;
                }

                string strProperty = string.Concat("@", pi.Name, "@");
                if (pi.PropertyType == typeof(DateTime))
                {
                    tempStrBuilder.Replace(strProperty, Convert.ToDateTime(o).ToString("yyyy-MM-dd"));
                }
                else
                {
                    tempStrBuilder.Replace(strProperty, o.ToString());
                }
            }
        }
        #endregion

        #region 附件

        /// <summary>
        /// 附件
        /// </summary>
        /// <param name="templateString"></param>
        /// <param name="contentId"></param>
        static public string AnnexList(string templateString, int contentId)
        {
            string strMode = templateString;

            int _ContentID = TagEngine.GetValue<int>(strMode, "ContentId");
 
            if (_ContentID == 0)
            {
                _ContentID = contentId;
            }
 

            IList<Annex> list = new AnnexManage().DataList(null, contentId);

            StringBuilder TempStrBuilder = new StringBuilder();
            strMode = TagEngine.GetString(templateString, "Annex", GetWhich.ItemTemplate);


            if (list.Count > 0)
            {
                foreach (Annex model in list)
                {
                    TempStrBuilder.Append(strMode);

                    PageCommon.RepalceFiled(TempStrBuilder, model);
                }
            }
            else
            {
                string _Temp = TagEngine.GetString(templateString, "Annex", GetWhich.EmptyDataTemplate);
                if (_Temp.Length == 0)
                    return string.Empty;
                else
                    TempStrBuilder.Append(_Temp);
            }

            return TempStrBuilder.ToString();
        }
        #endregion

        #region 生成友情链接
        /// <summary>
        /// 生成友情链接
        /// </summary>
        /// <param name="templateString"></param>
        /// <returns></returns>
        static public string FriendLink(string templateString)
        {
            StringBuilder strFriendLink = new StringBuilder();


            string strType = TagEngine.GetValue(templateString, "Type").ToLower();

            IList<FriendLink> list = new FriendLinkManage().BindList(strType, true);

            string strMode = TagEngine.GetString(templateString, "FriendLink", GetWhich.ItemTemplate);
            if (list.Count > 0)
            {
                foreach (FriendLink model in list)
                {
                    strFriendLink.Append(strMode);
                    PageCommon.RepalceFiled(strFriendLink, model);
                }
            }
            else
            {
                string _Temp = TagEngine.GetString(templateString, "FriendLink", GetWhich.EmptyDataTemplate);
                strFriendLink.Append(_Temp);
            }

            return strFriendLink.ToString();
        }
        #endregion

        #region 幻灯片
        /// <summary>
        /// 幻灯片
        /// </summary>
        /// <param name="templateString"></param>
        /// <returns></returns>
        public static string Slide(string templateString)
        {
            string strMode = templateString;

            int rows = TagEngine.GetValue<int>(strMode, "Rows");
            int categoryId = TagEngine.GetValue<int>(strMode, "CategoryId");
            if (categoryId == 0)
            {
                categoryId = int.Parse(HttpContext.Current.Request["CategoryId"]);
            }

            strMode = TagEngine.GetString(strMode, "Slide", GetWhich.InnerTemplate);

            var list = new CoreManage().SlideContents(rows, categoryId).ToArray();

            if (!list.Any())
            {
                return "";
            }
            string T = MyString.GetInnerString(strMode, "<TabTemplate>", "</TabTemplate>");
            string I = MyString.GetInnerString(strMode, "<ItemTemplate>", "</ItemTemplate>");

            StringBuilder tabTemplate = new StringBuilder();
            StringBuilder itemTemplate = new StringBuilder();
            for (int i = 0; i < list.Count(); i++)
            {
                if (T.Length > 0)
                {
                    tabTemplate.Append(T);
                    tabTemplate.Replace("@PageNo@", (i + 1).ToString());
                    PageCommon.RepalceFiled(tabTemplate, list[i]);
                }
                if (I.Length > 0)
                {
                    itemTemplate.Append(I);
                    PageCommon.RepalceFiled(itemTemplate, list[i]);
                }
            }
            if (T.Length > 0)
            {
                strMode = strMode.Replace(MyString.GetString(strMode, "<TabTemplate>", "</TabTemplate>"), tabTemplate.ToString());
            }
            if (I.Length > 0)
            {
                strMode = strMode.Replace(MyString.GetString(strMode, "<ItemTemplate>", "</ItemTemplate>"), itemTemplate.ToString());
            }
            return strMode;
        }
        #endregion




        #region 通用栏目列表
        /// <summary>
        /// 通用栏目列表
        /// </summary>
        /// <param name="webHtml"></param>
        /// <param name="model"></param>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public static string CategoryPageList(StringBuilder webHtml, Category model, int pageNo)
        {
            return PageList(webHtml, model.ModelId, model.Id, 0, null, null, pageNo);
        }
        /// <summary>
        /// 通用专题列表
        /// </summary>
        /// <param name="webHtml"></param>
        /// <param name="modelId"></param>
        /// <param name="specialId"></param>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public static string SpecialContetnList(StringBuilder webHtml, byte modelId, int specialId, int pageNo)
        {
            return PageList(webHtml, modelId, 0, specialId, null, null, pageNo);
        }

        /// <summary>
        /// 通用搜索列表
        /// </summary>
        /// <param name="webHtml"></param>
        /// <param name="modelId"></param>
        /// <param name="sort"></param>
        /// <param name="keyWord"></param>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public static string SearchContetnList(StringBuilder webHtml, byte modelId, string sort, string keyWord, int pageNo)
        {
            if (webHtml == null) throw new ArgumentNullException("webHtml");
            return PageList(webHtml, modelId, 0, 0, sort, keyWord, pageNo);
        }

        /// <summary>
        /// 配置处理
        /// </summary>
        /// <param name="webHtml"></param>
        /// <param name="modelId"></param>
        /// <param name="categoryId"></param>
        /// <param name="specialId"></param>
        /// <param name="sort"></param>
        /// <param name="keyWord"></param>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        static private string PageList(StringBuilder webHtml, byte modelId, int categoryId, int specialId, string sort, string keyWord, int pageNo)
        {
            string strMode = MyString.GetString(webHtml.ToString(), "<TW:PageList", "</TW:PageList>");

            PagingParam pp = new PagingParam
            {
                PageNo = pageNo,
                PageSize = ModelManage.GetPageSize(modelId)
            };

            IList<Core> list = null;
            if (categoryId > 0)
            {
                list = new CoreManage().CategoryPageBindList(categoryId, null, pp);
            }
            else if (specialId > 0)
            {
                list = new CoreManage().SpecialPageBindList(specialId, pp);
            }
            else if (string.IsNullOrEmpty(keyWord) == false)
            {
                list = new CoreManage().Search(sort, keyWord, pp);
            }

            BLL.PageFactory.HtmlFactory.UrlPager o = new BLL.PageFactory.HtmlFactory.UrlPager();
            {
                //CMSConfig config = CMSConfig.Instance();
                //if (config.UrlRewrite)
                //{
                //    o.EnableUrlRewrite = true;
                //}
                o.PageNo = pageNo;
                o.PageSize = pp.PageSize;
                o.RecordCount = pp.RecordCount;
                o.CssClass = "pager";
                o.CustomizeText = string.Format("<span>{0}</span>", pp.RecordCount);
                webHtml.Replace("@CutPage@", o.ToString());
            }

            webHtml.Replace(strMode, CategoryPageList(webHtml, list));

            return webHtml.ToString();
        }
        /// <summary>
        /// 数据处理
        /// </summary>
        /// <param name="webHtml"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        static private string CategoryPageList(StringBuilder webHtml, IList<Core> list)
        {
            StringBuilder winner = new StringBuilder(10240);

            if (list.Count > 0)
            {
                string strMode = MyString.GetString(webHtml.ToString(), "<TW:PageList", "</TW:PageList>");

                int titleLen = TagEngine.GetValue<int>(strMode, "TitleLen");//标题长度
                int briefLen = TagEngine.GetValue<int>(strMode, "BriefLen");//摘要长度

                string itemTemplate = TagEngine.GetString(webHtml.ToString(), "PageList", GetWhich.ItemTemplate);
                foreach (dynamic model in list)
                {
                    winner.Append(itemTemplate);

                    string title = model.ContentTitle;
                    string brief = MyString.Left(model.Brief, briefLen);

                    winner.Replace("@ContentTitle@", title);
                    if (titleLen > 0)
                    {
                        title = MyString.Left(title, titleLen);
                    }
                    winner.Replace("@ShortTitle@", title);

                    if (strMode.IndexOf("<IsOnTop>", StringComparison.CurrentCultureIgnoreCase) > -1)
                    {
                        if (model.IsOnTop)
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "IsOnTop", GetWhich.All), TagEngine.GetInnerModule(strMode, "IsOnTop", GetWhich.IsOnTop));
                        }
                        else
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "IsOnTop", GetWhich.All), "");
                        }
                    }


                    if (strMode.IndexOf("<IsElite>", StringComparison.CurrentCultureIgnoreCase) > -1)
                    {
                        if (model.IsElite)
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "IsElite", GetWhich.All), TagEngine.GetInnerModule(strMode, "IsElite", GetWhich.IsOnTop));
                        }
                        else
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "IsElite", GetWhich.All), "");
                        }
                    }
                    if (strMode.IndexOf("<Other>", StringComparison.CurrentCultureIgnoreCase) > -1)
                    {
                        if (model.IsChecked)
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "Other", GetWhich.All), TagEngine.GetInnerModule(strMode, "Other", GetWhich.IsOnTop));
                        }
                        else
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "Other", GetWhich.All), "");
                        }
                    }
                    if (strMode.IndexOf("<IsMember>", StringComparison.CurrentCultureIgnoreCase) > -1)
                    {
                        if (model.Rank > 0)
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "IsMember", GetWhich.All), TagEngine.GetInnerModule(strMode, "IsMember", GetWhich.IsOnTop));
                        }
                        else
                        {
                            winner.Replace(TagEngine.GetInnerModule(strMode, "IsMember", GetWhich.All), "");
                        }
                    }

                    if (strMode.IndexOf("<BriefTemplate>", StringComparison.CurrentCultureIgnoreCase) > -1)
                    {
                        winner.Replace(TagEngine.GetInnerModule(strMode, "BriefTemplate", GetWhich.All), ShowPicAndContent(model.PicUrl, brief, strMode));
                    }

                    PageCommon.RepalceFiled(winner, model);
                }
            }
            else
            {
                winner.Append("没有数据！<br/>");
            }
            return winner.ToString();
        }

        /// <summary>
        /// 根本图片存在否决定是否显示（文章、软件模块公用）
        /// </summary>
        /// <param name="picUrl"></param>
        /// <param name="brief"></param>
        /// <param name="strMode"></param>
        /// <returns></returns>
        static private string ShowPicAndContent(string picUrl, string brief, string strMode)
        {
            if (string.IsNullOrEmpty(picUrl))
            {
                return brief;
            }
            else
            {
                string strContentMode = TagEngine.GetInnerModule(strMode, "BriefTemplate", GetWhich.BriefTemplate);
                strContentMode = strContentMode.Replace("@PicUrl@", picUrl);
                strContentMode = strContentMode.Replace("@Brief@", brief);
                return strContentMode;
            }
        }
        #endregion

        #region  站内关键字

        public static string FormatBody(string body, int contentId)
        {
            Regex reg = new Regex(@"(<a .+?</a>)|(<pre(>|\s).+?</pre>)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match mat = reg.Match(body);
            IList<string> str1 = new List<string>();
            IList<string> str2 = new List<string>();
            int indx = 0;
            while (mat.Success)
            {
                str1.Add(body.Substring(indx, mat.Index - indx));
                str2.Add(mat.Value);
                indx = mat.Index + mat.Length;

                mat = reg.Match(body, indx);
            }
            str1.Add(body.Substring(indx));
            str2.Add("");

            StringBuilder sb = new StringBuilder();
            int p = 50, cnt, len;
            StringBuilder tmp;
            Regex reg2;
            Match mat2;

            TagsManage tm = new TagsManage();
            for (int i = 0; i < str1.Count; i++)
            {
                tmp = new StringBuilder(str1[i]);

                if (Regex.Replace(tmp.ToString(), @"<.+?>", "").Length > 5)
                {
                    cnt = tmp.Length / p;
                    len = 0;
                    foreach (Tag _tag in tm.AllTags(contentId))//AllTags包含了站内所有关键字
                    {
                        reg2 = new Regex(@"((^|>)[^<]+?)(" + _tag.TagName + ")", RegexOptions.IgnoreCase);
                        mat2 = reg2.Match(tmp.ToString());
                        if (mat2.Success)
                        {
                            tmp.Remove(mat2.Index, mat2.Length);
                            tmp.Insert(mat2.Index, mat2.Groups[1].Value + "<a href='/tag/" + mat2.Groups[2].Value + ".htm'>" + mat2.Groups[2].Value + "</a>");
                            if (++len > cnt) break;
                        }
                    }
                }
                sb.Append(tmp.ToString());
                sb.Append(str2[i]);
            }
            return sb.ToString();
        }

        #endregion


    }

}